package com.hippoframework.bean;
import java.util.Set;

import com.hippoframework.annotation.Component;
import com.hippoframework.config.ConfigConstants;
import com.hippoframework.config.Environment;
import com.hippoframework.utils.AnnotationUtils;
import com.hippoframework.utils.ClassUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author TylerW
 * @date 5/4/2020 3:32 PM
 */
@Slf4j
public class BeanRegistry {

    /**
     * 扫描Class，生成BeanDefinition
     */
    @SneakyThrows
    public static void registerDefinition(BeanFactory beanFactory, Environment environment) {
        log.info("开始扫描Component...");
        Set<Class<?>> totalClass = ClassUtils.getClassSet(ConfigConstants.HIPPO_BASE_PACKAGE);
        for (Class<?> cls : totalClass) {
            //根据Class解析Component
            if (AnnotationUtils.isAnnotationContains(cls, Component.class)) {
                if (ClassUtils.isAssignable(cls, FactoryBean.class)) {
                    //解析FactoryBean
                    GenericBeanDefinition definition = new GenericBeanDefinition();
                    FactoryBean<?> factoryBean = (FactoryBean<?>) cls.newInstance();
                    definition.setFactoryBean(factoryBean);
                    beanFactory.doRegisterDefinition(factoryBean.getObjectType(), definition);
                }
                beanFactory.doRegisterDefinition(cls, new GenericBeanDefinition());
            }
        }
        log.info("Component扫描结束，共计:{}", beanFactory.getBeanDefinitions().size());
    }


}
